/* eslint-disable max-lines */
import {host} from "@/configs/run";
import {request, requestDuration, requestMethod, requestType} from "@/common/request";
import {Modal} from "ant-design-vue";
import {decodeAesString} from "@/common/crypto";

// Api 类
export class Api {
  __url = "";

  __method = requestMethod.GET;

  __type = requestType.DEFAULT;

  __auth = localStorage.getItem("token");

  __data = {};

  __params = {};

  __query = [];

  __timeout = requestDuration.STANDARD;

  __hint = "";

  __responseType = "";

  __req = null;

  constructor(url, getHost) {
    this.url(url, getHost);
  }

  url(url, getHost = (t) => t) {
    this.__url = `${getHost(host)}/${url}`;
    return this;
  }

  method(method) {
    this.__method = method;
    return this;
  }

  type(type) {
    this.__type = type;
    return this;
  }

  auth(auth) {
    this.__auth = auth;
    return this;
  }

  data(data) {
    this.__data = data;
    return this;
  }

  params(params) {
    this.__params = params;
    return this;
  }

  query(query) {
    this.__query = query;
    return this;
  }

  responseType(responseType) {
    this.__responseType = responseType;
    return this;
  }

  timeout(timeout) {
    this.__timeout = timeout;
  }

  hint(hint) {
    this.__hint = hint;
    return this;
  }

  __requestFn() {
    let queryUrl = this.__query.reduce((pre, cur) => `${pre}/${cur}`, "");
    this.__req = request({
      url: `${this.__url}${queryUrl}`,
      method: this.__method,
      type: this.__type,
      responseType: this.__responseType,
      headers: {
        Authorization: this.__auth,
      },
      timeout: this.__timeout,
      qs: ![requestType.JSON, requestType.FILE].includes(this.__type),
    }, this.__data, this.__params);
  }

  async send() {
    let modelStatus = null;
    if (this.__hint) {
      modelStatus = new Promise((resolve, reject) => {
        Modal.confirm({
          title: "提示",
          content: `确定要${this.__hint}吗？`,
          centered: true,
          onOk: () => {
            this.__requestFn();
            resolve();
          },
          onCancel: () => {
            resolve();
          },
        });
      });
    } else {
      this.__requestFn();
      modelStatus = Promise.resolve(null);
    }
    await modelStatus;
    return this;
  }

  async getDatas() {
    const res = (await this.__req) || {};
    if (this.__hint && res.hasOwnProperty("code")) {
      if (res.code === 0) {
        Modal.success({
          title: "提示",
          content: `${this.__hint}成功`,
          centered: true,
        });
      } else {
        Modal.error({
          title: "提示",
          content: `${this.__hint}失败${res.msg ? `,${res.msg}` : ""}`,
          centered: true,
        });
      }
    }
    return res;
  }
}

